package com.codding.springboot_mybatisdemo.service.Impl;

import com.codding.springboot_mybatisdemo.entity.Users;
import com.codding.springboot_mybatisdemo.mapper.UserMapper;
import com.codding.springboot_mybatisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Users> selectAll() {
        List<Users> users = userMapper.selectAll();
        return users;
    }

    @Override
    public List<Users> selectByCondition(Integer userId, String userName, String userTel, String userSex, Integer minScore, Integer maxScore) {
        int temp = 0;
        if (minScore != null && maxScore != null) {
            if (minScore.compareTo(maxScore) > 0){
                temp = minScore;
                minScore = maxScore;
                maxScore = temp;
            }
        }

        //调用mapper完成条件查询
        List<Users> users = userMapper.selectByDynamic(userId, userName, userTel, userSex, minScore, maxScore);

        return users;
    }

    @Override
    public boolean deleteUserById(Integer userId) {
        // 调用 MyBatis 的 Mapper 删除用户
        try {
            int rowsAffected = userMapper.deleteUserById(userId);
            return rowsAffected > 0; // 如果删除成功，返回 true
        } catch (Exception e) {
            e.printStackTrace();
            return false; // 如果发生异常，返回 false
        }
    }

    @Override
    public boolean addUser(Users user) {
        try {
            // 调用 mapper 插入用户
            int rowsAffected = userMapper.insertUser(user);
            return rowsAffected > 0; // 如果插入成功，返回 true
        } catch (Exception e) {
            e.printStackTrace();
            return false; // 如果发生异常，返回 false
        }
    }
}
